package com.ycsj.goldmedalnewconcept.common.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.ycsj.common.adapter.VpCommonAdapter;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.utils.DeleteFileUtil;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.view.vp.SuperViewPager;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.WordPreInfo;
import com.ycsj.goldmedalnewconcept.common.fragment.EmptyFragment;
import com.ycsj.goldmedalnewconcept.common.fragment.WordsYxFragment;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.TestTimeCountUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 预习-词汇预习
 * Created by Administrator on 2019/4/3 0003.
 */

public class WordsPrepareActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.vp)
    SuperViewPager vp;
    @BindView(R.id.tv_page)
    TextView tvPage;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.ll_content)
    LinearLayout llContent;

    //Vp适配器
    private VpCommonAdapter adapter;

    //Vp填充的Fragment
    private List<Fragment> mFragments;

    //单元的lessonId
    private String lessonId;

    //单元号
    private String unit;

    //所有问题的集合
    private List<WordPreInfo.QuestionListBean> questions;

    //请求参数
    private String acc, role, apptoken;

    //跳转到第一页的标识
    public static final int GOONE = 0x640;

    //计时的ID
    private String rid;

    /**
     * 跳转到当前页面的方法
     */
    public static void goActivity(Context context, String lessonId, String unit) {
        Intent it = new Intent(context, WordsPrepareActivity.class);
        it.putExtra("lessonId", lessonId);
        it.putExtra("unit", unit);
        context.startActivity(it);
    }


    @Override
    protected int getContentLayout() {
        return R.layout.activity_words_prepare;
    }

    @Override
    protected void init() {
        initStateBar();

        //获取Intent
        initIntent();

        //初始化请求参数
        initParams();

        //初始化状态
        initState();


//        applyPermission();

        //请求页面数据
        http();
    }

    /**
     * 动态申请权限
     */
    private void applyPermission() {

        Boolean result = PermissionX.isGranted(this, Manifest.permission.WRITE_SETTINGS);

        LogUtils.iTag("test", "权限的结果是:" + result);

        if (result) {
            //有权限

        } else {
            //没有权限
            PermissionX.init(this)
                    .permissions(Manifest.permission.WRITE_SETTINGS)
                    .request(new RequestCallback() {
                        @Override
                        public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                            if (allGranted) {
//                                call()
                            } else {
//                                Log.d("TAG", "onResult: ---");
                            }
                        }
                    });
        }
    }


    /**
     * 初始化请求参数
     */
    private void initParams() {
        acc = AccountUtils.getAccount(this);
        role = AccountUtils.getRole(this);
        apptoken = AccountUtils.getToken(this);
    }

    /**
     * 获取Intent对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra("lessonId");
        unit = getIntent().getStringExtra("unit");
    }

    /**
     * 初始化状态
     */
    private void initState() {
        rlLoading.setVisibility(View.VISIBLE);
        llContent.setVisibility(View.GONE);
        vp.addOnPageChangeListener(this);
    }

    /**
     * 请求页面数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", acc);
        map.put("role", role);
        map.put("lessonid", lessonId);
        map.put("token1", apptoken);
        map.put("platform", "2");
        HttpUtils.get(HttpAddress.WORDPREPARE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                rlLoading.setVisibility(View.GONE);
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {

                rlLoading.setVisibility(View.GONE);

                if (!TextUtils.isEmpty(response)) {
                    WordPreInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, WordPreInfo.class);
                    } catch (Exception e) {
                        ToastUtils.showShort(Constants.PARSEDATAERROR);
                    }

                    if (null != info && "200".equals(info.getState())) {
                        //取出所有题的数据
                        questions = info.getQuestion_list();

                        if (null == questions || questions.size() == 0) {
                            //证明没有问题
                            ToastUtils.showShort("暂无数据返回");
                        } else {
                            //有问题
                            llContent.setVisibility(View.VISIBLE);
                            //设置页面数据
                            setPageData();
                        }
                    }
                } else {
                    ToastUtils.showShort(Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 设置页面数据
     */
    private void setPageData() {
        mFragments = new ArrayList<>();
        for (int i = 0; i < questions.size(); i++) {
            mFragments.add(WordsYxFragment.newInstance(
                    questions.get(i), i, String.valueOf(lessonId)));
        }

        mFragments.add(EmptyFragment.newInstance(lessonId));

        // 第一步:设置底部的展示当前题目的TextView
        tvPage.setText("第1" + "/" + (questions.size())
                + "道题<---左滑下一题");

        // 第二步:设置顶部标题的文字
        tvTitle.setText(questions.get(0).getQuestion_content());
//        tvTitle.setText("词汇预习");
        // 第三步:给Vp设置适配器
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);

        vp.setOffscreenPageLimit(0);
    }


    /**
     * ViewPager的滚动监听事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int pos) {
        // 如果不是最后一页则执行以下操作
        if (pos != mFragments.size() - 1) {
            // 第一步:同步标题栏的文字
            tvTitle.setText(questions.get(pos).getQuestion_content());
//            tvTitle.setText("词汇预习");

            // 第二步:同步底部显示页面的文字
            tvPage.setVisibility(View.VISIBLE);
            tvPage.setText("第" + (pos + 1) + "/"
                    + (questions.size()) + "道题<---左滑下一题");

            // 第三步:同步播放器的状态,防止翻页时音频没有停止
            BusInfo info = new BusInfo();
            info.type = WordsYxFragment.STOPPLAY;
            EventBus.getDefault().post(info);
        } else {
            tvPage.setVisibility(View.INVISIBLE);
            tvTitle.setText("词汇预习");
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {


    }


    @Override
    protected void onResume() {
        super.onResume();
        TestTimeCountUtil.startTime(this, "3", String.valueOf(lessonId).substring(0, 4), lessonId, new TestTimeCountUtil.onSuccessListener() {
            @Override
            public void onSuccess(String infoRid) {
                rid = infoRid;
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        TestTimeCountUtil.stopTime(this, rid);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
        }
    }

    /**
     * 处理事件
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && GOONE == busInfo.type) {
            vp.setCurrentItem(0);
        }
    }

    /**
     *
     */
    @Override
    protected void onDestroy() {
        //清空所有的录音文件
        DeleteFileUtil.deleteDirectory(getExternalCacheDir().getAbsolutePath()
                + "/msc/");
        super.onDestroy();
    }
}
